package com.xyy.controller;

import com.xyy.entity.Feedback;
import com.xyy.entity.Admin;
import com.xyy.service.FeedbackService;
import com.xyy.service.AdminService;
import com.xyy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 反馈控制器
 */
@RestController
@RequestMapping("/feedback")
public class FeedbackController {
    
    @Autowired
    private FeedbackService feedbackService;
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 添加反馈
     */
    @PostMapping("/add")
    public Map<String, Object> addFeedback(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从JWT token中获取用户ID
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            // 移除Bearer前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取参数
            String content = (String) params.get("content");
            String images = (String) params.get("images");
            Long adminId = params.get("adminId") != null ? Long.valueOf(params.get("adminId").toString()) : null;
            String adminRealName = (String) params.get("adminRealName");
            
            if (content == null || content.trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "反馈内容不能为空");
                return result;
            }
            
            // 创建反馈对象
            Feedback feedback = new Feedback(userId, adminId, adminRealName, content, images);
            
            // 添加反馈
            boolean success = feedbackService.addFeedback(feedback);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "反馈提交成功");
                result.put("data", feedback);
            } else {
                result.put("code", 500);
                result.put("message", "反馈提交失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取反馈详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> getFeedbackDetail(@PathVariable Long id, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证用户身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取反馈详情
            Feedback feedback = feedbackService.getFeedbackById(id);
            
            if (feedback == null) {
                result.put("code", 404);
                result.put("message", "反馈不存在");
                return result;
            }
            
            // 检查是否是用户自己的反馈
            if (!feedback.getUserId().equals(userId)) {
                result.put("code", 403);
                result.put("message", "无权限查看此反馈");
                return result;
            }
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", feedback);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取用户反馈列表
     */
    @GetMapping("/list")
    public Map<String, Object> getUserFeedbacks(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证用户身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取用户反馈列表
            List<Feedback> feedbacks = feedbackService.getFeedbacksByUserId(userId);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", feedbacks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取用户已处理的反馈列表
     */
    @GetMapping("/resolved")
    public Map<String, Object> getResolvedFeedbacks(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证用户身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取已处理反馈列表
            List<Feedback> feedbacks = feedbackService.getResolvedFeedbacks(userId);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", feedbacks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取用户未处理的反馈列表
     */
    @GetMapping("/pending")
    public Map<String, Object> getPendingFeedbacks(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证用户身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取未处理反馈列表
            List<Feedback> feedbacks = feedbackService.getPendingFeedbacks(userId);
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", feedbacks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 删除反馈
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteFeedback(@PathVariable Long id, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证用户身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 检查反馈是否存在且属于当前用户
            Feedback feedback = feedbackService.getFeedbackById(id);
            if (feedback == null) {
                result.put("code", 404);
                result.put("message", "反馈不存在");
                return result;
            }
            
            if (!feedback.getUserId().equals(userId)) {
                result.put("code", 403);
                result.put("message", "无权限删除此反馈");
                return result;
            }
            
            // 删除反馈
            boolean success = feedbackService.deleteFeedback(id);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取管理员列表（用于反馈功能）
     * 返回简化的管理员信息，只包含ID和真实姓名
     */
    @GetMapping("/admin-names")
    public Map<String, Object> getAdminNames() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Admin> admins = adminService.getAllAdmins();
            List<Map<String, Object>> adminNames = admins.stream()
                .map(admin -> {
                    Map<String, Object> adminInfo = new HashMap<>();
                    adminInfo.put("id", admin.getId());
                    adminInfo.put("realName", admin.getRealName());
                    return adminInfo;
                })
                .collect(java.util.stream.Collectors.toList());
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", adminNames);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据管理员ID获取已处理的反馈列表
     */
    @GetMapping("/admin/{adminId}/processed")
    public Map<String, Object> getProcessedFeedbacksByAdmin(@PathVariable Long adminId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证管理员身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long currentAdminId = jwtUtil.getAdminIdFromToken(token);
            if (currentAdminId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 检查权限：只能查看自己的反馈或超级管理员可以查看所有
            Admin currentAdmin = adminService.getAdminById(currentAdminId);
            if (currentAdmin == null) {
                result.put("code", 401);
                result.put("message", "管理员不存在");
                return result;
            }
            
            // 如果不是超级管理员且不是查看自己的反馈，则无权限
            if (currentAdmin.getLevel() != 2 && !currentAdminId.equals(adminId)) {
                result.put("code", 403);
                result.put("message", "无权限查看其他管理员的反馈");
                return result;
            }
            
            // 获取该管理员的已处理反馈列表
            List<Feedback> feedbacks = feedbackService.getFeedbacksByAdminId(adminId);
            // 过滤已处理的反馈
            List<Feedback> processedFeedbacks = feedbacks.stream()
                .filter(feedback -> "RESOLVED".equals(feedback.getStatus()) || "REJECTED".equals(feedback.getStatus()))
                .collect(java.util.stream.Collectors.toList());
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", processedFeedbacks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 根据管理员ID获取未处理的反馈列表
     */
    @GetMapping("/admin/{adminId}/pending")
    public Map<String, Object> getPendingFeedbacksByAdmin(@PathVariable Long adminId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证管理员身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long currentAdminId = jwtUtil.getAdminIdFromToken(token);
            if (currentAdminId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 检查权限：只能查看自己的反馈或超级管理员可以查看所有
            Admin currentAdmin = adminService.getAdminById(currentAdminId);
            if (currentAdmin == null) {
                result.put("code", 401);
                result.put("message", "管理员不存在");
                return result;
            }
            
            // 如果不是超级管理员且不是查看自己的反馈，则无权限
            if (currentAdmin.getLevel() != 2 && !currentAdminId.equals(adminId)) {
                result.put("code", 403);
                result.put("message", "无权限查看其他管理员的反馈");
                return result;
            }
            
            // 获取该管理员的未处理反馈列表
            List<Feedback> feedbacks = feedbackService.getFeedbacksByAdminId(adminId);
            // 过滤未处理的反馈
            List<Feedback> pendingFeedbacks = feedbacks.stream()
                .filter(feedback -> "PENDING".equals(feedback.getStatus()) || "PROCESSING".equals(feedback.getStatus()))
                .collect(java.util.stream.Collectors.toList());
            
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", pendingFeedbacks);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 更新反馈状态和添加回复
     */
    @PutMapping("/admin/update/{id}")
    public Map<String, Object> updateFeedbackStatus(@PathVariable Long id, @RequestBody Map<String, Object> params, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证管理员身份
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                result.put("code", 401);
                result.put("message", "未登录");
                return result;
            }
            
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long adminId = jwtUtil.getAdminIdFromToken(token);
            if (adminId == null) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 获取参数
            String status = (String) params.get("status");
            String adminReply = (String) params.get("adminReply");
            
            if (status == null || status.trim().isEmpty()) {
                result.put("code", 400);
                result.put("message", "状态不能为空");
                return result;
            }
            
            // 验证状态值
            if (!"PENDING".equals(status) && !"PROCESSING".equals(status) && 
                !"RESOLVED".equals(status) && !"REJECTED".equals(status)) {
                result.put("code", 400);
                result.put("message", "无效的状态值");
                return result;
            }
            
            // 检查反馈是否存在
            Feedback feedback = feedbackService.getFeedbackById(id);
            if (feedback == null) {
                result.put("code", 404);
                result.put("message", "反馈不存在");
                return result;
            }
            
            // 检查权限：只能处理分配给自己的反馈或超级管理员可以处理所有
            Admin admin = adminService.getAdminById(adminId);
            if (admin == null) {
                result.put("code", 401);
                result.put("message", "管理员不存在");
                return result;
            }
            
            // 如果不是超级管理员且不是处理分配给自己的反馈，则无权限
            if (admin.getLevel() != 2 && !adminId.equals(feedback.getAdminId())) {
                result.put("code", 403);
                result.put("message", "无权限处理此反馈");
                return result;
            }
            
            // 更新反馈状态和回复
            boolean success = feedbackService.updateFeedbackStatus(id, status, adminReply);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "更新成功");
                
                // 返回更新后的反馈信息
                Feedback updatedFeedback = feedbackService.getFeedbackById(id);
                result.put("data", updatedFeedback);
            } else {
                result.put("code", 500);
                result.put("message", "更新失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "系统错误：" + e.getMessage());
        }
        
        return result;
    }
}
